package com.msb.common.exception;

import com.msb.common.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一的异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handlerValidException(MethodArgumentNotValidException e){
        Map<String,String> map = new HashMap<>();
        e.getFieldErrors().forEach((fieldError)->{
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return CommonResult.error(BizErrorCodeEnum.VALID_EXCEPTION.getCode(), BizErrorCodeEnum.VALID_EXCEPTION.getMsg(), map);
    }

    /**
     * 系统其他的异常处理
     * @param throwable
     * @return
     */
    @ExceptionHandler(Exception.class)
    public CommonResult handlerException(Exception throwable){
        log.error("错误信息：",throwable);
        return CommonResult.error(BizErrorCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizErrorCodeEnum.UNKNOWN_EXCEPTION.getMsg(), throwable.getMessage());
    }
}
